package com.wohuijituan.whcsmerchant.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.wohuijituan.whcsmerchant.R;
import com.wohuijituan.whcsmerchant.activity.GoodsCompileActivity;
import com.wohuijituan.whcsmerchant.adapter.GoodsListAdapter;
import com.wohuijituan.whcsmerchant.bean.CommonBean;
import com.wohuijituan.whcsmerchant.bean.ShopGoodsListBean;
import com.wohuijituan.whcsmerchant.callback.CommonCallBack;
import com.wohuijituan.whcsmerchant.url.ParamsKey;
import com.wohuijituan.whcsmerchant.url.Urls;
import com.wohuijituan.whcsmerchant.utils.ExtraName;
import com.wohuijituan.whcsmerchant.utils.LogUtils;
import com.wohuijituan.whcsmerchant.utils.MyOkHttpUtils;
import com.wohuijituan.whcsmerchant.utils.MyRequestParams;
import com.wohuijituan.whcsmerchant.utils.MyUtile;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

import static com.wohuijituan.whcsmerchant.fragment.GoodsSellFragment.EditRequestCode;
import static com.wohuijituan.whcsmerchant.fragment.GoodsSellFragment.GoodsStateSet_OK;
import static com.wohuijituan.whcsmerchant.fragment.GoodsSellFragment.GoodsStoreSet_OK;
import static com.wohuijituan.whcsmerchant.fragment.GoodsSellFragment.ShopGoodsList_OK;

/**
 * Created by zsy_18 on 2016/12/30.
 */

public class ShopGoodsSearchFragment extends MyBaseFragment implements View.OnClickListener {
    public static final String TAG = "ShopGoodsSearchFragment";
    private GoodsListAdapter myAdapter;
    private PullToRefreshListView pullGoodsList;
    private LinearLayout llGoodsCompile;
    private LinearLayout llGoodsUnShelve;
    private LinearLayout llGoodsRemainCompile;
    private LinearLayout popLayout;

    private void assignViews(View v) {
        llGoodsCompile = (LinearLayout) v.findViewById(R.id.ll_goods_compile);
        llGoodsUnShelve = (LinearLayout) v.findViewById(R.id.ll_goods_un_shelve);
        llGoodsRemainCompile = (LinearLayout) v.findViewById(R.id.ll_goods_remain_compile);
    }
    private MyOkHttpUtils myOkHttpUtils;
    private MyRequestParams params;
    private int nowPage = 1;//当前显示页数
    private int totalPage;//订单总页数
    private String keyWord = "";//搜索的关键字
    private int pageNumber = 10;//每页显示个数
    private int position;//当前弹窗代表的商品条目位置
    private List<ShopGoodsListBean.DataEntity.GoodsEntity> goodsList;
    @Override
    protected View createMyView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_goods_list, container, false);
        initData();
        initView(v);
        initListener();
        return v;
    }

    private void initData() {
        myOkHttpUtils = new MyOkHttpUtils();
        params = new MyRequestParams();
        goodsList = new ArrayList<>();
        myAdapter = new GoodsListAdapter(ctx, goodsList);
    }

    private void initView(View v) {
        //初始化界面
        pullGoodsList = (PullToRefreshListView) v.findViewById(R.id.pull_goods_list);
        pullGoodsList.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        //得到弹窗控件,并得到其内部控件
        popLayout = (LinearLayout) LayoutInflater.from(ctx).inflate(R.layout.pop_compile_goods, pullGoodsList, false);
        assignViews(popLayout);
        pullGoodsList.setAdapter(myAdapter);
        llGoodsCompile.setOnClickListener(this);
        llGoodsRemainCompile.setOnClickListener(this);
        llGoodsUnShelve.setOnClickListener(this);
        myAdapter.setMyOnItemBtnClickListener(new GoodsListAdapter.MyOnItemBtnClickListener() {
            @Override
            public void onClick(int position, View view) {
                LogUtils.e(TAG, view.getLeft() + "***" + view.getRight());
                ShopGoodsSearchFragment.this.position = position;
                showPopupWindow(view);
            }
        });
    }
    private void initListener() {
        llGoodsCompile.setOnClickListener(this);
        llGoodsRemainCompile.setOnClickListener(this);
        llGoodsUnShelve.setOnClickListener(this);
        myAdapter.setMyOnItemBtnClickListener(new GoodsListAdapter.MyOnItemBtnClickListener() {
            @Override
            public void onClick(int position, View view) {
                LogUtils.e(TAG, view.getLeft() + "***" + view.getRight());
                ShopGoodsSearchFragment.this.position = position;
                showPopupWindow(view);
            }
        });
        pullGoodsList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (nowPage < totalPage) {
                    //TODO 得到下一页数据

                } else {
                    showToast(ctx, "已经是最后一页");
                    pullGoodsList.onRefreshComplete();
                }

            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_goods_compile://编辑商品
                ShopGoodsListBean.DataEntity.GoodsEntity data = goodsList.get(position);
                Intent intent = new Intent(getActivity(), GoodsCompileActivity.class);
                intent.putExtra(ExtraName.SHOPGOODS_BEAN, data);
                intent.putExtra(ExtraName.TAG, TAG);
                startActivityForResult(intent, EditRequestCode);
                popWindow.dismiss();
                break;
            case R.id.ll_goods_un_shelve://下架商品
                data = goodsList.get(position);
                // TODO: 2016/12/30
                popWindow.dismiss();
                break;
            case R.id.ll_goods_remain_compile://余量编辑机
                data = goodsList.get(position);
                showCompileDialog(data.getSMC_GUID());
                popWindow.dismiss();
                break;
        }
    }

    PopupWindow popWindow;

    /**
     * 弹窗编辑商品
     *
     * @param v
     */
    private void showPopupWindow(View v) {

        popWindow = new PopupWindow(
                popLayout,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
                , true);
        popWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_pop));
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        LogUtils.e(TAG, "location[0]" + location[0] + "v.getWidth()" + v.getWidth() + "popLayout.getWidth()" + popLayout.getWidth());
        int x = -v.getWidth() - MyUtile.getViewHeight(popLayout, false);
        int y = -v.getMeasuredHeight() / 2 - MyUtile.getViewHeight(popLayout, true) / 2;
//        popWindow.showAtLocation(v, (location[0]-v.getWidth()-popLayout.getWidth()), location[1]-v.getHeight()/2);
        popWindow.showAsDropDown(v, x, y);
    }
    /**
     * 弹出一个dialog让用户修改信息
     * @param shopGoodsSN 当前商家的商品列表中商品的唯一标示
     */
    private void showCompileDialog(final String shopGoodsSN){
        final EditText et = new EditText(activity);
        et.setSingleLine(true);
        //直接调出输入数字软键盘
        et.setInputType(InputType.TYPE_CLASS_NUMBER );

        new AlertDialog.Builder(activity).setTitle("库存")
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String input = et.getText().toString();
                        if (input.equals("")) {
                            showToast(activity,"输入不能为空");
                        } else {
                            int store = Integer.parseInt(input);
                            goodsStoreEditRequest(shopGoodsSN,store);
                        }
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 进行搜索,public方法,外部调用
     * @param keyWord
     */
    public void doSearchGoods(String keyWord){

    }

    /**
     * 搜索商品的网络请求
     * @param keyWord
     */
    private void searchGoodsRequest(String keyWord,int pageIndex,int rows){
        showDialog(ctx);
        params.clear();
        String strUrl = Urls.ShopGoodsSearch;
        params.addStringRequest(ParamsKey.UserKey,myApplication.getUserKey());
        params.addStringRequest(ParamsKey.ShopGoodsSearch_KeyWord,keyWord);
        params.addStringRequest(ParamsKey.ShopGoodsList_PageIndex,pageIndex+"");
        params.addStringRequest(ParamsKey.ShopGoodsSearch_Rows,rows+"");
//        myOkHttpUtils.postRequest(strUrl,params,new );
    }
    /**
     * 商品余量编辑请求方法
     * @param shopGoodsSN
     * @param store
     */
    private void goodsStoreEditRequest(String shopGoodsSN, final int store){
        showDialog(ctx);
        String strUrl = Urls.GoodsStoreEdit;
        params.clear();
        params.addStringRequest(ParamsKey.GoodsStoreEdit_GoodsGUID, shopGoodsSN);
        params.addStringRequest(ParamsKey.GoodsEdit_Store,store+"");
        myOkHttpUtils.postRequest(strUrl, params, new CommonCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast(ctx, "网络出错,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
                dismissDialog();
            }

            @Override
            public void onResponse(CommonBean response, int id) {
                dismissDialog();
                if (response.getState() == 1) {
                    Message msg = new Message();
                    msg.what = GoodsStoreSet_OK;
                    msg.obj = store;
                    handler.sendMessage(msg);
                    showToast(ctx, "操作成功:" + response.getMsg());
                } else {
                    showToast(ctx, "操作失败:" + response.getMsg());
                }
            }
        });
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case ShopGoodsList_OK:
                    // 商品列表请求成功
                    ShopGoodsListBean bean = (ShopGoodsListBean) msg.obj;
                    nowPage = bean.getData().getPageIndex();
                    totalPage = bean.getData().getPageCount();
                    if (nowPage ==1){
                        myAdapter.replace(bean.getData().getData());
                        LogUtils.e(TAG, nowPage + "数据个数:" + bean.getData().getData().size());
                    }else if (nowPage>1){
                        myAdapter.addAll(bean.getData().getData());
//                        goodsList.addAll(bean.getData().getData());
//                        myAdapter.notifyDataSetChanged();
                    }
                    dismissDialog();
                    break;
                case GoodsStateSet_OK:
                    // TODO: 2016/12/30  商品上架、下架成功
                    myAdapter.sub(position);
                    break;
                case GoodsStoreSet_OK:
                    //TODO 商品库存修改成功
                    int store = (int) msg.obj;
                    goodsList.get(position).setSMC_StockNum(store);
                    myAdapter.notifyDataSetChanged();

            }
        }
    };
}
